﻿namespace DataIntegration.Utils.Lifecycle.Base
{
    using System;
    using System.Reflection;
    using log4net;

    public abstract class BaseLifecycle : ILifecycle
    {
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private readonly object sync;

        private bool started;

        protected BaseLifecycle()
        {
            Logger.DebugFormat("Creating BaseLifecycle");
            this.sync = new object();
        }

        public abstract void Dispose();

        protected abstract void Setup();

        public void Start()
        {
            Logger.DebugFormat("Start requested");
            if (!this.started)
            {
                lock (this.sync)
                {
                    if (!this.started)
                    {
                        Logger.DebugFormat("Start required - delegating to derived class");
                        this.Setup();
                        this.started = true;
                    }
                    else
                    {
                        Logger.DebugFormat("Already running - Start being skipped");
                    }
                }   
            }
            else
            {
                Logger.DebugFormat("Already running - Start being skipped");
            }
        }

        protected void Dispose(IDisposable disposable)
        {
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
    }
}